import os
import sys
from debug import *
import hashlib
import tempfile
import shutil
import tarfile

class package:
    def __init__(self ,services):
        self.services = services;
        self.initPath = os.getcwd();


    def getServiceObj(self, serviceName):
        if self.services.has_key(serviceName):
            return self.services[serviceName]
        else:
            return NULL;


    def checkFiles(self,serviceName):
        service = self.getServiceObj(serviceName)
        if not service:
             print "NO SERVICE:"+serviceName;
             exit(1)
        if not service.install:
             print "NO INSTALL SET:"+serviceName;
             exit(1)
        if not os.path.isdir(service.destination):
            print "check files error , no directory",service.destination;
            exit(1);
        os.chdir(service.destination)
        installStr = service.install
        installs = installStr.split();
        for install in installs:
            if os.path.isdir(install) or os.path.isfile(install):
                 continue;
            else:
                 print "no file or directory "+install+ " in "+serviceName
                 return False;
        os.chdir(self.initPath)
        print "FINISH CHECK "+serviceName+", ALL INSTALL FILE EXISTS."
        return True;

    def checkAllFiles(self):
        for ins in self.services.keys():
            if self.checkFiles(ins):
                continue;
            else :
                return False;
        return True;

    def MD5File(self, fileName):
        try:
            f = file(fileName,'rb')
        except:
            print 'Failed to open file '+file;
            exit;
        m = hashlib.md5();
        while True:
            d = f.read(8096)
            if not d:
                break;
            m.update(d)
        return m.hexdigest()

    def packageFile(self,serviceName):
        if not self.checkFiles(serviceName):
            exit(1)
        tempf = tempfile.mkdtemp();
        service = self.getServiceObj(serviceName)
        print "make temp directory ",tempf
        installs  = service.install.split()
        for install in installs:
            if os.path.islink(install):
               print "THERE ARE LINK IN INSTALL...PANIC!!!!"
            filePath = os.path.join ( service.destination , install );
            os.system("mkdir -p  "+os.path.dirname( os.path.join(tempf,install)))
            os.system("cp -rfa "+filePath+"  "+os.path.join(tempf,install))


        os.chdir(service.destination)
        md5file = file(os.path.join( tempf, "MD5SUM" ), "wb");
        for install in installs:
            if os.path.isfile(install):
                md5file.writelines(install+ "   "+self.MD5File( install )+"\n")
            elif os.path.isdir(install):
                for parent, dirnames, filenames in os.walk(install):
                    if len(filenames):
                        for filename in filenames:
                            rePath = os.path.join( parent, filename );
                            md5file.writelines( rePath+ "       "+self.MD5File( rePath )+"\n")
        md5file.close()
        os.chdir(self.initPath)

        tar = tarfile.open(serviceName+".tar", "w")
        os.chdir(tempf)
        tar.add(".")
        os.chdir(self.initPath)
        tar.close()

